﻿<template>
  <el-dialog v-drag :title = 'dialogSelectTitle' :visible.sync = 'dialogSelectVisible' :width = 'dialogWidth' :before-close = 'closeDialog'
  class = 'md_dialog'>
    <el-form ref = 'ruleForm' :model = 'formModel' :rules = 'editRules'>
      <el-form-item :label = 'dialogLabel' prop = 'editData'>
        <!-- 下拉框 -->
        <el-select :disabled = "editInfo.status === 'show'"
          filterable v-if = "editInfo.item.ui_type === 'Select'" clearable v-model = 'formModel.editData' placeholder = '请选择'>
          <el-option v-for='(selectItem, select$Index) in selectOptions' :key='selectItem[showValue] + select$Index' :label="selectItem[showValue]"
          :value='selectItem[selectValue]'></el-option>
        </el-select>
        <!-- pop弹窗 -->
        <div v-else-if = "editInfo.item.ui_type === 'Pop' || editInfo.item.ui_type === 'MultiPop'">
          <br>
          <Pop-Select ref = "myPopSelect" :disabled = "editInfo.status === 'show'"
          :defaultValue.sync = 'formModel.editData' :showPopDialog = 'showDialog'
          :editElementObj = 'editInfo' :currentPageModelsObj = 'editInfo.row' from = 'meta'></Pop-Select>
        </div>
        <!-- 富文本编辑器 -->
        <div v-else-if="editInfo.item.ui_type === 'RichText'">
          <br>
          <Tinymce-Component ref = "myTinymce" :disabled = "editInfo.status === 'show'"
          :defaultValue.sync = 'formModel.editData' :showTinymce = 'showEditDialog'></Tinymce-Component>
        </div>
        <!-- MD编辑器 -->
        <div v-else-if = "editInfo.item.ui_type === 'MD'">
          <br>
          <Editor-Md ref = "myMD" :disabled = "editInfo.status === 'show'"
          :defaultValue.sync = 'formModel.editData' :showMD = 'showEditDialog'></Editor-Md>
        </div>
        <!-- JSONEditor编辑器 -->
        <div v-else-if = "editInfo.item.ui_type === 'JSONEditor'">
          <br>
          <Editor-Md-Json ref = "myJSONEditor" :disabled = "editInfo.status === 'show'"
          :defaultValue.sync = 'formModel.editData' :showMDJson = 'showEditDialog'></Editor-Md-Json>
        </div>
        <!-- 文件 -->
        <div v-else-if="editInfo.item.ui_type === 'File'">
          <el-button type="text" v-if='formModel.editData' @click="handleDownload" class='upload_dowmload'>{{downloadName}}</el-button>
          <br>
          <el-upload ref='upload' :action='actionUrl' :file-list='fileList' :limit='1' :auto-upload="false" drag class='uploadContent' :on-change='changePic' :on-remove = 'removeUpload'
          :on-exceed='onExceed' :http-request='httpRequest' v-show="editInfo.status === 'edit'">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </div>
        <!-- 图片 -->
        <div v-else-if="editInfo.item.ui_type === 'Picture'">
          <el-button type="text" v-if='formModel.editData' @click="handleDownload" class='upload_dowmload'>{{downloadName}}</el-button>
          <br>
          <el-upload ref='upload' :action='actionUrl' :file-list='fileList' :limit='1' :auto-upload="false" class="upload_imgContent" :on-change='changePic' :on-remove = 'removeUpload'
          accept='.png, .jpg, .jpeg, .gif' list-type="picture" :on-exceed='onExceed' :http-request='httpRequest' :disabled="editInfo.status === 'show'">
            <el-image style = 'width:100%;height:100%'  class = "show_uploadPic" v-if = "imageUrl && editInfo.status !== 'edit'"
            :src = "imageUrl" :preview-src-list = 'previewSrcList'></el-image>
            <img v-if="imageUrl && editInfo.status === 'edit'" :src="imageUrl" class="upload_img">
            <i v-if="editInfo.status === 'edit'" class="el-icon-plus upload_imgIcon"></i>
            <span class="upload_noImg" v-if="editInfo.status === 'show' && !imageUrl">
              <p><i class='icon-cloud iconfont'></i></p>
              <p>暂无图片</p>
            </span>
            <span v-if="editInfo.status === 'edit'">点击上传图片</span>
          </el-upload>
        </div>
        <!-- 地图 -->
        <div v-else-if = "editInfo.item.ui_type === 'MapXY'">
          <span v-if = "editInfo.status === 'edit'">请点击地图获取经纬度</span>
          <span v-if = "editInfo.status === 'show'">查看该字段的经纬度信息</span>
          <br>
          <div>
            <p style='margin-bottom:10px;margin-right: 20px;display:inline-block'>经度为：<el-input disabled id='getLng'></el-input></p>
            <p style='margin-bottom:10px;display:inline-block'>纬度为：<el-input disabled id='getLat'></el-input></p>
            <div id='myMap' v-if="editInfo.item.ui_type === 'MapXY'"></div>
          </div>
        </div>
        <!-- 地图Gis -->
        <div v-else-if = "editInfo.item.ui_type === 'GIS_Draw_Line'">
          <el-row style = 'margin-bottom: 5px;' :gutter = '20'>
            <el-col :span = '5' v-if = "editInfo.status === 'edit'">
              <span>左键点击地图开始绘制,点击右键完成绘制</span>
            </el-col>
            <el-col :span = '4'>
              <el-input v-model = 'drawArea' placeholder = '请输入需要展示的行政区、市或省名称' :disabled = "editInfo.status === 'show'">
                <el-button v-if = "editInfo.status !== 'show'" slot = "append" @click = 'drawBounds'>绘制区域</el-button>
              </el-input>
            </el-col>
            <el-col :span = '2' class = 'el-input-group__prepend_row'>
              <el-input :disabled = "editInfo.status === 'show'" v-model = 'drawRoadCity' placeholder = '道路所属城市'></el-input>
            </el-col>
            <el-col :span = '4' class = 'el-input-group__prepend_row'>
              <el-input v-model = 'drawRoad' placeholder = '请输入道路名称' :disabled = "editInfo.status === 'show'">
                <el-button v-if = "editInfo.status !== 'show'" slot = "append" @click = 'drawRoadMethod'>绘制道路</el-button>
              </el-input>
            </el-col>
            <el-col :span = '6' class = 'el-input-group__prepend_row'>
              <el-input v-model = 'drawRoadEnd' placeholder = '请输入道路终点' :disabled = "editInfo.status === 'show'">
                <el-input slot = "prepend" :disabled = "editInfo.status === 'show'" v-model = 'drawRoadStart' placeholder = '请输入道路起点'></el-input>
                <el-button v-if = "editInfo.status !== 'show'" slot = "append" @click = 'drawRoadMethodStart'>绘制道路</el-button>
              </el-input>
            </el-col>
          </el-row>
          <div id = 'myMap_Gis' v-if = "editInfo.item.ui_type === 'GIS_Draw_Line'"></div>
        </div>
        <!-- 图片获取位置 -->
        <div v-else-if="editInfo.item.ui_type === 'PicXY'">
          <br>
          <div v-if = 'picImgSrc'>
            <p style='margin-bottom:10px;'>该点距左上角left值为：<el-input disabled v-model='picX'></el-input></p>
            <p style='margin-bottom:10px;'>该点距左上角top值为：<el-input disabled v-model='picY'></el-input></p>
            <div class='outContent'>
              <div class='innerContent'>
                <div id='pickImgContent'>
                  <img @click = "editInfo.status === 'edit' ? getClickPoint($event) : ''" :src="picImgSrc" alt="">
                  <span class='locationIcon' v-if='picX' :style="{left: picX - 17 + 'px', top: picY - 20 + 'px'}"
                  ><i class='iconfont icon-guiji'></i>
                  </span>
                </div>
              </div>
            </div>
          </div>
          <div v-else>暂无图片信息</div>
        </div>
      </el-form-item>
    </el-form>
    <span slot="footer" v-show="editInfo.status === 'edit'">
      <el-button type="info" @click="handleClose('ruleForm')">取 消</el-button>
      <el-button type = "primary" @click = "reDraw" v-if = "editInfo.item.ui_type === 'GIS_Draw_Line'">重 绘</el-button>
      <el-button type="primary" @click="handleSubmit('ruleForm')">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import axios from 'axios'
import TinymceComponent from '@/components/Tinymce/TinymceComponent'
// MD编辑器
import EditorMd from '@/components/EditorMd/EditorMd'
// JSONEditor编辑器
import EditorMdJson from '@/components/EditorMd/EditorMdJson'
// pop弹窗
import PopSelect from '@/components/MetaFormItemComponents/PopSelect.vue'
export default {
  props: ['editInfo', 'showEditDialog'],
  components: { TinymceComponent, EditorMd, EditorMdJson, PopSelect },
  data () {
    return {
      dialogSelectVisible: false,
      dialogSelectTitle: '编辑字段信息',
      formModel: {
        editData: ''
      },
      dialogLabel: '',
      // select
      selectValue: '',
      showValue: '',
      selectOptions: [],
      // 上传部分
      actionUrl: '',
      fileList: [],
      fileReader: '',
      imageUrl: '',
      previewSrcList: [],
      isDownload: false,
      downloadName: '',
      hadNewFile: false,
      // 表单验证
      editRules: {
        editData: []
      },
      // 获取图片时
      picImgSrc: '',
      picX: '',
      picY: '',
      location: {
        lng: null,
        lat: null
      },
      map: null,
      // 绘制道路的点的数组
      pathArray: [],
      // 绘制行政区域
      district: null,
      polygons: [],
      // 绘制区域
      drawArea: '',
      // 绘制道路
      drawRoadCity: '武汉市',
      drawRoad: '',
      // 道路起点和终点
      drawRoadStart: '',
      drawRoadEnd: '',
      defaultPathArray: [] // 检索的道路路径数组
    }
  },
  mounted () {
    if (!window.FileReader) {
      this.$message({
        message: '您的浏览器不支持 FileReader API',
        type: 'warning'
      })
    } else {
      this.fileReader = new FileReader()
    }
  },
  computed: {
    dialogWidth () {
      if (this.editInfo.item.ui_type === 'RichText') {
        return '95%'
      } else if (this.editInfo.item.ui_type === 'MD' || this.editInfo.item.ui_type === 'JSONEditor') {
        return '95%'
      } else if (this.editInfo.item.ui_type === 'MapXY' || this.editInfo.item.ui_type === 'GIS_Draw_Line') {
        return '95%'
      } else if (this.editInfo.item.ui_type === 'Pop' || this.editInfo.item.ui_type === 'MultiPop') {
        return '85%'
      } else if (this.editInfo.item.ui_type === 'PicXY') {
        return '855px'
      } else {
        return '35%'
      }
    }
  },
  methods: {
    // 上传文件或者图片改变时
    changePic () {
      this.hadNewFile = true
    },
    // 上传文件移除
    removeUpload () {
      this.hadNewFile = false
    },
    // 上传文件时
    httpRequest (options) {
      let file = options.file
      let filename = file.name
      let fileLength = file.size
      if (file) {
        this.fileReader.readAsDataURL(file)
      }
      this.fileReader.onload = () => {
        this.loading = true
        let base64Str = this.fileReader.result
        axios({
          url: $URL.IMG_UPLOAD_URL + '/fileset/upload',
          method: 'post',
          data: {
            file_name: filename,
            file_length: fileLength,
            file_content: base64Str.split(',')[1]
          }
        }).then(data => {
          if (data.data.result.code === 'success') {
            this.$message({
              message: '上传成功',
              type: 'success'
            })
            this.$refs.upload.clearFiles()
            this.formModel.editData = data.data.result.link_url
            this.$emit('sureEdit', this.formModel.editData)
          } else {
            this.$message({
              message: data.data.result.msg,
              type: 'error'
            })
          }
          this.loading = false
        }).catch(error => {
          console.log(error)
        })
      }
    },
    // 点击下载文件时
    handleDownload () {
      this.isDownload = true
      this.downloadFile()
    },
    // 下载文件时
    downloadFile () {
      this.loading = true
      if (this.formModel.editData && this.formModel.editData.indexOf('~') === 0) {
        this.$get('/s_table/' + this.editInfo.funUid + '/dl', {
          path: encodeURIComponent(this.formModel.editData)
        }).then(data => {
          let dataInfo = data.data.result
          if (dataInfo.code === 'success') {
            let content = decodeURIComponent(dataInfo.file)
            this.imageUrl = 'data:image/png;base64,' + content
            this.previewSrcList = [this.imageUrl]
            this.downloadName = decodeURIComponent(dataInfo.filename)
            // 点击下载文件时，需要打开浏览器的下载功能
            if (this.isDownload) {
              let blobContent = this.toBlob(content, dataInfo.filetype)
              this.downloadblob(blobContent, dataInfo.filename)
            }
          } else if (dataInfo.code === 'failed') {
            this.$message({
              message: dataInfo.msg,
              type: 'error'
            })
          }
          this.loading = false
        }).catch(error => {
          console.log(error)
        })
      } else {
        if (this.formModel.editData) {
          axios({
            url: this.formModel.editData,
            method: 'get'
          }).then(data => {
            let dataInfo = data.data.result
            if (dataInfo.code === 'success') {
              let content = decodeURIComponent(dataInfo.file)
              this.imageUrl = 'data:image/png;base64,' + content
              this.previewSrcList = [this.imageUrl]
              this.downloadName = decodeURIComponent(dataInfo.filename)
              if (this.isDownload) {
                let blobContent = this.toBlob(content, dataInfo.filetype)
                this.downloadblob(blobContent, dataInfo.filename)
              }
            } else if (dataInfo.code === 'failed') {
              this.$message({
                message: dataInfo.msg,
                type: 'error'
              })
            }
            this.loading = false
          }).catch(error => {
            console.log(error)
          })
        }
      }
    },
    // 下载的相关方法
    downloadblob (blobcontent, filename) {
      if ('msSaveOrOpenBlob' in navigator) {
        // Microsoft Edge and Microsoft Internet Explorer 10-11
        window.navigator.msSaveOrOpenBlob(blobcontent, filename)
      } else {
        // 创建隐藏的可下载链接
        var eleLink = document.createElement('a')
        eleLink.download = filename
        eleLink.style.display = 'none'
        // 字符内容转变成blob地址
        eleLink.href = URL.createObjectURL(blobcontent)
        // 触发点击
        document.body.appendChild(eleLink)
        eleLink.click()
        // 然后移除
        document.body.removeChild(eleLink)
      }
    },
    toBlob (base64str, filetype) {
      let bytes = window.atob(base64str)
      let n = bytes.length
      let u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bytes.charCodeAt(n)
      }
      return new Blob([u8arr], {type: filetype})
    },
    // 文件超过最大上传个数时
    onExceed (files, fileList) {
      this.$message({
        message: '一次只能上传一个文件，请先移除文件列表中的文件，在选择需要上传的文件',
        type: 'warning'
      })
    },
    // 获取pop或者select的option
    getPop (columnName) {
      this.table.tableData = []
      this.loading = true
      this.$patch('/s_table/pop/' + this.editInfo.funUid + '/' + columnName).then(data => {
        let dataInfo = data.data.result
        if (dataInfo.code === 'failed') {
          this.$message({
            message: dataInfo.msg,
            type: 'error'
          })
        } else if (dataInfo.code === 'success') {
          if (this.editInfo.item.ui_type === 'Select') {
            this.selectOptions = []
            this.selectValue = dataInfo.column_value
            if (dataInfo.data.length) {
              dataInfo.data.forEach((val, index) => {
                this.$set(this.selectOptions, index, val)
              })
            }
            this.showValue = dataInfo.column_show[0].column_name
          }
        }
        this.loading = false
      }).catch(error => {
        console.log(error)
      })
    },
    // 检索/绘制道路的方法---根据道路名称
    drawRoadMethod () {
      var _self = this
      _self.defaultPathArray = []
      if (!_self.drawRoad) {
        _self.$message({
          message: '请输入道路名称',
          type: 'warning'
        })
        return
      }
      _self.$confirm('确定要执行绘制道路的操作么,该操作将清空已绘制的道路?', '提示', {
        confirmButtonText: '确定',
        cancelButtonClass: 'el-button--info',
        cancelButtonText: '取消'
      }).then(() => {
        AMap.service(['AMap.RoadInfoSearch'], function () {
          var roadSearch = new AMap.RoadInfoSearch({
            pageSize: 100,
            pageIndex: 1,
            city: _self.drawRoadCity ? _self.drawRoadCity : ''
          })
          // 关键字查询
          roadSearch.roadInfoSearchByRoadName(_self.drawRoad, function (status, result) {
            if (status === 'no_data') {
              _self.$message({
                message: '没有获取到道路信息',
                type: 'warning'
              })
              return
            }
            let hadTheSameRoad = false
            if (result && result.roadInfo && result.roadInfo.length) {
              result.roadInfo.forEach(item => {
                if (item.name === _self.drawRoad && item.path && item.path.length) {
                  hadTheSameRoad = true
                  _self.map.clearMap() // 清空已绘制的路线
                  _self.pathArray = []
                  // 绘制行政区域
                  _self.drawBounds(1)
                  for (let i = 0; i < item.path.length; i++) {
                    _self.$set(_self.defaultPathArray, _self.defaultPathArray.length, item.path[i])
                    const polyline = new AMap.Polyline({
                      path: item.path[i],
                      strokeWeight: 2, // 线条宽度，默认为 1
                      strokeColor: 'blue', // 线条颜色
                      zIndex: 40,
                      lineJoin: 'round' // 折线拐点连接处样式
                    })
                    _self.map.add(polyline)
                  }
                  _self.map.setFitView()
                }
              })
            }
            if (!hadTheSameRoad) {
              _self.$message({
                message: '没有获取到道路信息',
                type: 'warning'
              })
            }
          })
        })
      }).catch(() => {})
    },
    // 检索/绘制道路的方法---根据道路起始点
    drawRoadMethodStart () {
      var _self = this
      _self.defaultPathArray = []
      if (!_self.drawRoadCity) {
        _self.$message({
          message: '请输入道路所属城市',
          type: 'warning'
        })
        return
      }
      if (!_self.drawRoadStart) {
        _self.$message({
          message: '请输入道路起点名称',
          type: 'warning'
        })
        return
      }
      if (!_self.drawRoadEnd) {
        _self.$message({
          message: '请输入道路终点名称',
          type: 'warning'
        })
        return
      }
      _self.$confirm('确定要执行绘制道路的操作么,该操作将清空已绘制的道路?', '提示', {
        confirmButtonText: '确定',
        cancelButtonClass: 'el-button--info',
        cancelButtonText: '取消'
      }).then(() => {
        AMap.service(['AMap.Driving'], function () {
          var drivingSearch = new AMap.Driving({
            policy: AMap.DrivingPolicy.LEAST_DISTANCE // LEAST_DISTANCE最短距离,LEAST_TIME最快捷模式,LEAST_FEE最经济模式,REAL_TRAFFIC考虑实时路况
          })
          // 关键字查询
          drivingSearch.search([
            { keyword: _self.drawRoadStart, city: _self.drawRoadCity },
            { keyword: _self.drawRoadEnd, city: _self.drawRoadCity }
          ], function (status, result) {
            if (status === 'no_data') {
              _self.$message({
                message: '没有获取到道路信息',
                type: 'warning'
              })
              return
            }
            if (result && result.routes && result.routes.length && result.routes[0].steps && result.routes[0].steps.length) {
              _self.map.clearMap() // 清空已绘制的路线
              _self.pathArray = []
              // 绘制行政区域
              _self.drawBounds(1)
              result.routes[0].steps.forEach(item => {
                _self.$set(_self.defaultPathArray, _self.defaultPathArray.length, item.path)
                const polyline = new AMap.Polyline({
                  path: item.path,
                  strokeWeight: 2, // 线条宽度，默认为 1
                  strokeColor: 'blue', // 线条颜色
                  zIndex: 40,
                  lineJoin: 'round' // 折线拐点连接处样式
                })
                _self.map.add(polyline)
              })
              _self.map.setFitView()
            } else {
              _self.$message({
                message: '没有获取到道路信息',
                type: 'warning'
              })
            }
          })
        })
      }).catch(() => {})
    },
    // 绘制道路时
    reDraw () {
      var _self = this
      // 重新绘制的方法
      if (_self.map) {
        _self.map.clearMap()
        _self.pathArray = []
        _self.defaultPathArray = []
        // 绘制行政区域
        _self.drawBounds()
      }
    },
    // 初始化地图--绘制道路时
    initGisMap () {
      var _self = this
      _self.pathArray = []
      _self.defaultPathArray = []
      _self.drawArea = ''
      // 高德地图API功能
      /* global AMap */
      /* global AMAP_ANIMATION_BOUNCE */
      _self.map = new AMap.Map('myMap_Gis', {
        resizeEnable: true,
        zoom: 16,
        zooms: [3, 20],
        expandZoomRange: true
      }) // 创建Map实例
      // 数据格式为JSON字符串:{path: [], drawArea: ''}
      if (this.formModel.editData && this.formModel.editData.length) {
        let initDataObj = JSON.parse(this.formModel.editData)
        _self.defaultPathArray = (initDataObj.path && initDataObj.path.length) ? initDataObj.path : []
        _self.drawArea = initDataObj.drawArea
        _self.drawRoadCity = initDataObj.drawRoadCity
        _self.drawRoad = initDataObj.drawRoad
        _self.drawRoadStart = initDataObj.drawRoadStart
        _self.drawRoadEnd = initDataObj.drawRoadEnd
      }
      // 绘制行政区域
      _self.drawBounds()
      // 有道路时,就进行绘制
      if (_self.defaultPathArray.length) {
        for (let i = 0; i < _self.defaultPathArray.length; i++) {
          let polyline = new AMap.Polyline({
            path: _self.defaultPathArray[i],
            strokeColor: _self.editInfo.status === 'show' ? 'red' : 'blue',
            strokeWeight: _self.editInfo.status === 'show' ? 8 : 2,
            strokeOpacity: 1,
            zIndex: _self.editInfo.status === 'show' ? 50 : 40,
            strokeStyle: 'solid', // dashed
            lineJoin: 'round' // 折线拐点连接处样式
          })
          _self.map.add(polyline)
        }
      }
      // 当为可编辑状态时
      if (_self.editInfo.status !== 'show') {
        let mouseTool = new AMap.MouseTool(_self.map)
        mouseTool.polyline({
          strokeColor: 'red',
          strokeWeight: 8,
          zIndex: 50,
          strokeOpacity: 1,
          strokeStyle: 'solid', // dashed
          lineJoin: 'round'
        })
        // 绘制完成时
        mouseTool.on('draw', function (e) {
          if (e.obj && e.obj.Ce && e.obj.Ce.path && e.obj.Ce.path.length) {
            _self.$set(_self.pathArray, _self.pathArray.length, e.obj.Ce.path)
          }
        })
      }
    },
    // 绘制行政区域的方法
    drawBounds (noSetView) {
      let _self = this
      if (!_self.drawArea) {
        if (_self.defaultPathArray && _self.defaultPathArray.length && !noSetView) {
          _self.map.setZoomAndCenter(14, new AMap.LngLat(_self.defaultPathArray[0][0].lng, _self.defaultPathArray[0][0].lat))
        }
        return
      }
      // 加载行政区划插件
      if (!_self.district) {
        // 实例化DistrictSearch
        var opts = {
          subdistrict: 0, // 获取边界不需要返回下级行政区
          extensions: 'all', // 返回行政区边界坐标组等具体信息
          level: 'district' // 查询行政级别为 市
        }
        _self.district = new AMap.DistrictSearch(opts)
      }
      // 行政区查询
      _self.district.search(_self.drawArea, function (status, result) {
        if (status === 'no_data') {
          _self.$message({
            message: '请输入正确的区域名称',
            type: 'warning'
          })
          return
        }
        _self.map.remove(_self.polygons) // 清除上次结果
        _self.polygons = []
        var bounds = result.districtList[0].boundaries
        if (bounds) {
          for (var i = 0, l = bounds.length; i < l; i++) {
            // 生成行政区划polygon
            var polygon = new AMap.Polygon({
              strokeWeight: 1,
              path: bounds[i],
              fillOpacity: 0.2,
              fillColor: 'red',
              strokeColor: 'red'
            })
            _self.polygons.push(polygon)
          }
        }
        _self.map.add(_self.polygons)
        if (!noSetView) {
          _self.map.setFitView(_self.polygons) // 视口自适应
          if (_self.defaultPathArray && _self.defaultPathArray.length) {
            _self.map.setZoomAndCenter(14, new AMap.LngLat(_self.defaultPathArray[0][0].lng, _self.defaultPathArray[0][0].lat))
          }
        }
      })
    },
    // 初始化地图
    initMap () {
      var _self = this
      if (_self.formModel.editData) {
        let splitA = _self.formModel.editData.split(',')
        _self.$set(_self.location, 'lat', splitA[1])
        _self.$set(_self.location, 'lng', splitA[0])
      } else {
        _self.$set(_self.location, 'lat', null)
        _self.$set(_self.location, 'lng', null)
      }
      // 高德地图API功能
      /* global AMap */
      /* global AMAP_ANIMATION_BOUNCE */
      _self.map = new AMap.Map('myMap', {
        resizeEnable: true,
        zoom: 16,
        zooms: [3, 20],
        expandZoomRange: true
      }) // 创建Map实例
      var point = ''
      if (_self.location.lat) {
        point = new AMap.LngLat(_self.location.lng, _self.location.lat)
        let markers = new AMap.Marker({
          position: point,
          animation: 'AMAP_ANIMATION_BOUNCE'
        })
        _self.map.add(markers)
      } else {
        point = new AMap.LngLat(114.307274, 30.544488)
      }
      _self.map.setCenter(point) // 设置地图显示的中心点
      if (_self.editInfo.status === 'edit') {
        _self.map.on('click', function (e) {
          var pt = e.lnglat
          _self.$set(_self.location, 'lat', pt.lat)
          _self.$set(_self.location, 'lng', pt.lng)
          point = new AMap.LngLat(pt.lng, pt.lat)
          _self.map.clearMap()
          let markers = new AMap.Marker({
            position: point,
            animation: 'AMAP_ANIMATION_BOUNCE'
          })
          _self.map.add(markers)
        })
      }
    },
    // 获取图片的信息
    getPicInfo (columnName) {
      this.loading = true
      this.$patch('/s_table/pop/picxy/' + this.editInfo.funUid + '/' + columnName, {
        this_data: btoa(encodeURIComponent(JSON.stringify(this.editInfo.row)))
      }).then(data => {
        let dataInfo = data.data.result
        if (dataInfo.code === 'success') {
          let content = decodeURIComponent(dataInfo.file)
          this.picImgSrc = 'data:image/png;base64,' + content
          if (this.formModel.editData) {
            let splitA = this.formModel.editData.split(',')
            this.picX = splitA[0]
            this.picY = splitA[1]
          } else {
            this.picX = ''
            this.picY = ''
          }
        } else {
          this.picImgSrc = ''
          this.$message({
            message: dataInfo.msg,
            type: 'warning'
          })
        }
        this.loading = false
      })
    },
    // 获取点击点的位置
    getClickPoint (event) {
      this.picX = event.offsetX
      this.picY = event.offsetY
    },
    // 点击上部的X关闭弹窗时
    handleClose (forms) {
      this.$refs[forms].resetFields()
      this.$emit('giveUp')
      if (this.editInfo.item.ui_type === 'File' || this.editInfo.item.ui_type === 'Picture') {
        this.$refs.upload.abort()
        this.$refs.upload.clearFiles()
      }
    },
    closeDialog () {
      this.$refs.ruleForm.clearValidate()
      this.$emit('giveUp')
      if (this.editInfo.item.ui_type === 'File' || this.editInfo.item.ui_type === 'Picture') {
        this.$refs.upload.abort()
        this.$refs.upload.clearFiles()
      }
    },
    // 点击确定按钮时
    handleSubmit (forms) {
      this.$refs[forms].validate((valid) => {
        if (valid) {
          if (this.formModel.editData === '' && this.editInfo.item.ui_type === 'Switch') {
            this.formModel.editData = true
            this.$emit('sureEdit', this.formModel.editData)
            // 清空表单验证
            this.$refs.ruleForm.clearValidate()
          } else if (this.editInfo.item.ui_type === 'File' || this.editInfo.item.ui_type === 'Picture') {
            if (this.hadNewFile) {
              this.$refs.upload.submit()
            } else {
              this.$refs.ruleForm.clearValidate()
              this.$emit('giveUp')
              this.$refs.upload.abort()
              this.$refs.upload.clearFiles()
            }
          } else if (this.editInfo.item.ui_type === 'MapXY') {
            if (this.location.lat) {
              this.formModel.editData = this.location.lng + ',' + this.location.lat
            }
            this.$emit('sureEdit', this.formModel.editData)
          } else if (this.editInfo.item.ui_type === 'GIS_Draw_Line') {
            let dataArray = []
            if (this.pathArray && this.pathArray.length) {
              dataArray = JSON.parse(JSON.stringify(this.pathArray))
            } else {
              if (this.defaultPathArray && this.defaultPathArray.length) {
                dataArray = JSON.parse(JSON.stringify(this.defaultPathArray))
              }
            }
            // 数据格式为JSON字符串:{path: [], drawArea: ''}
            let dataObj = {
              path: dataArray,
              drawArea: this.drawArea,
              drawRoad: this.drawRoad,
              drawRoadCity: this.drawRoadCity,
              drawRoadStart: this.drawRoadStart,
              drawRoadEnd: this.drawRoadEnd
            }
            this.$emit('sureEdit', JSON.stringify(dataObj))
          } else if (this.editInfo.item.ui_type === 'PicXY') {
            if (this.picX) {
              this.formModel.editData = this.picX + ',' + this.picY
            }
            this.$emit('sureEdit', this.formModel.editData)
          } else if (this.editInfo.item.ui_type === 'MD') {
            // 获取MD的值
            this.$refs.myMD.getMdValue()
            this.$nextTick(() => {
              this.$emit('sureEdit', this.formModel.editData)
            })
          } else if (this.editInfo.item.ui_type === 'JSONEditor') {
            // 获取JSONEditor的值
            this.$refs.myJSONEditor.getMdValue()
            if (this.formModel.editData === 'JsonError') {
              return
            }
            this.$nextTick(() => {
              this.$emit('sureEdit', this.formModel.editData)
            })
          } else if (this.editInfo.item.ui_type === 'MultiPop' || this.editInfo.item.ui_type === 'Pop') {
            // 获取pop的值
            this.$refs.myPopSelect.getPopValue()
            this.$nextTick(() => {
              this.$emit('sureEdit', this.formModel.editData)
            })
            this.$emit('sureEdit', this.formModel.editData)
          } else {
            this.$emit('sureEdit', this.formModel.editData)
            // 清空表单验证
            this.$refs.ruleForm.clearValidate()
          }
        } else {
          return false
        }
      })
    }
  },
  watch: {
    showEditDialog: {
      handler: function (val, oldVal) {
        this.dialogSelectVisible = val
        if (this.map) { // 注销地图对象，并清空地图容器
          this.map.destroy()
          this.map = null
        }
        if (val) {
          // 获取需要展示的字段的描叙和name
          this.dialogLabel = this.editInfo.item.column_desc + ': '
          let clickItem = this.editInfo.item.column_name
          this.formModel.editData = this.editInfo.row[clickItem]
          // 对表单进行验证
          if (this.editInfo.item.check_required) {
            this.editRules.editData = [
              {required: true, message: this.dialogLabel + '不能为空', trigger: 'blur'}
            ]
          }
          if (this.editInfo.item.check_regex) {
            this.editRules.editData = [
              {pattern: this.editInfo.item.check_regex, message: '所填内容不满足要求', trigger: 'blur'}
            ]
          }
          if (!this.editInfo.item.check_regex && !this.editInfo.item.check_required) {
            this.editRules.editData = []
          }
          if (this.editInfo.item.ui_type !== 'MapXY' || this.editInfo.item.ui_type !== 'PicXY') {
            this.editRules.editData = []
          }
          // 当为图片或文件的时候
          if (this.editInfo.item.ui_type === 'Picture' || this.editInfo.item.ui_type === 'File') {
            this.imageUrl = ''
            this.previewSrcList = []
            this.downloadName = ''
            if (this.editInfo.row[clickItem]) {
              this.isDownload = false
              this.downloadFile()
            }
          }
          // 当为地图时
          if (this.editInfo.item.ui_type === 'MapXY') {
            this.$nextTick(() => [
              this.initMap()
            ])
          }
          // 当为地图时--绘制道路
          if (this.editInfo.item.ui_type === 'GIS_Draw_Line') {
            this.$nextTick(() => {
              this.initGisMap()
            })
          }
          // 当为图片时
          if (this.editInfo.item.ui_type === 'PicXY') {
            this.getPicInfo(clickItem)
          }
          // 当为弹窗的时候
          if (this.editInfo.item.ui_type === 'Select') {
            this.getPop(clickItem)
          }
          if (this.editInfo.status === 'show') {
            this.dialogSelectTitle = '查看字段信息'
          } else {
            this.dialogSelectTitle = '编辑字段信息'
          }
        }
      },
      deep: true
    }
  }
}
</script>

<style lang='scss' scoped>
#myMap{
  width:100%;
  height: 500px;
}
#myMap_Gis {
  width:100%;
  height: 700px;
}
#pickImgContent{
  width:100%;
  height:500px;
  overflow: auto;
  position:relative;
  img{
    cursor:pointer;
  }
  .locationIcon{
    position:absolute;
    width:30px;
    height:30px;
    text-align:center;
    line-height:30px;
    i{
      font-size:30px;
      color:red;
    }
  }
}
.outContent{
  position:relative;
  width:100%;
  height:500px;
}
.innerContent{
  position:absolute;
  width:100%;
  left:0;
  top:0;
  z-index:1000;
}
@media (max-height: 768px) {
  #myMap_Gis {
    width:100%;
    height: 500px;
  }
}
</style>
